package com.imay.base.manager;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created by nick on 2017/8/1.
 * 自行维护的Activity 栈
 */

public class ActivityStackManager {

    private static Stack<Activity> activityStack;

    private static class ActivityStackManagerHolder {
        private static final ActivityStackManager INSTANCE = new ActivityStackManager();
    }

    public static final ActivityStackManager getInstance() {
        return ActivityStackManagerHolder.INSTANCE;
    }

    private ActivityStackManager() {
        activityStack = new Stack<>();
    }

    public void addActivity(Activity activity) {

        activityStack.add(activity);
    }

    public void clearActivitys(Class targetActivity) {
        List<Activity> activityList = new ArrayList<>();
        while (true) {
            if (activityStack.isEmpty()) {
                break;
            }
            Activity activity = activityStack.lastElement();
            if (activity != null) {
                activityStack.remove(activity);
                activityList.add(activity);
                if (activity.getClass().equals(targetActivity)) {
                    for (Activity activity1 : activityList) {
                        activity1.finish();
                    }
                    break;
                }
            } else {
                break;
            }
        }


    }

    public void clearAll() {
        if (activityStack != null && !activityStack.isEmpty()) {
            activityStack.clear();
        }

    }





}
